package com.h2cloud.ReactorTest.reactor.server;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Package: com.h2cloud.ReactorTest.reactor.server
 * @ClassName: Acceptor
 * @Author: wulongkai
 * @CreateTime: 2024/7/23 15:53
 * @Description:
 */
public class Acceptor implements Runnable {

    private final Selector selector;
    private final ServerSocketChannel listenSocketChannel;

    public Acceptor(Selector selector, ServerSocketChannel listenSocketChannel) {
        this.selector = selector;
        this.listenSocketChannel = listenSocketChannel;
    }

    @Override
    public void run() {
        try {
            // 为连接的客户端创建client-socket管道
            SocketChannel clientSocketChannel = listenSocketChannel.accept();
            System.out.println(String.format("收到来自 %s 的连接", clientSocketChannel.getRemoteAddress()));
            // 设置为非阻塞
            clientSocketChannel.configureBlocking(false);
            // READ事件的附加器是Handler
            clientSocketChannel.register(selector, SelectionKey.OP_READ,
                    new AsynHandler(clientSocketChannel));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

